package com.itclj.common.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;

import org.im4java.core.IM4JavaException;

import com.itclj.common.base.RequestData;

public class ImageUtil {

	private static final Logger logger = Logger.getLogger(ImageUtil.class.getName());

	/**
	 * 图片压缩
	 * 
	 * @param fullPath
	 *            文件路径
	 * @param imgRatio
	 *            图片是否等比例压缩，1：等比例压缩，0：不等比例压缩
	 * @param imgWidth
	 *            图片宽度(px)
	 * @param imgHeight
	 *            图片高度(px)
	 */
	public static void compress(String fullPath, String imgRatio, int imgWidth, int imgHeight) {

		ThreadPoolUtil.getInstance().getFixedThreadPool().execute(new Runnable() {
			public void run() {
				// 图片是否等比例压缩，1：等比例压缩，0：不等比例压缩
				int imgWidthI = imgWidth;
				int imgHeightI = imgHeight;
				if (RequestData.ImgRatio.YES.equals(imgRatio)) {

					// 等比例压缩计算图片
					int imgWidthM = 0;
					int imgHeightM = 0;
					imgWidthI = imgWidth > 0 ? imgWidth : 1;
					imgHeightI = imgHeight > 0 ? imgHeight : 1;
					try {
						FileInputStream fis = new FileInputStream(new File(fullPath));
						BufferedImage bufferedImg = ImageIO.read(fis);
						imgWidthM = bufferedImg.getWidth();
						imgHeightM = bufferedImg.getHeight();
						fis.close();
					} catch (IOException e) {
						logger.log(Level.WARNING, "图片压缩错误，IO异常" + e);
					}

					float whm = (float) imgWidthM / (float) imgHeightM;
					float wh = (float) imgWidth / (float) imgHeight;
					if (whm > wh) {
						if (imgWidthI > imgWidthM) {
							imgWidthI = imgWidthM;
						}
						imgHeightI = (int) (imgWidthI / whm);
					} else {
						if (imgHeightI > imgHeightM) {
							imgHeightI = imgHeightM;
						}
						imgWidthI = (int) (imgHeightI * whm);
					}
				}
				try {
					IM4JavaUtil.cropImageCenter(fullPath, fullPath, imgWidthI, imgHeightI);
				} catch (IOException e) {
					logger.log(Level.WARNING, "IM4Java图片压缩出错，" + e);
				} catch (InterruptedException e) {
					logger.log(Level.WARNING, "IM4Java图片压缩出错，" + e);
				} catch (IM4JavaException e) {
					logger.log(Level.WARNING, "IM4Java图片压缩出错，" + e);
				}
			}
		});
	}
}
